package com.musicconvert.controller;

import com.musicconvert.service.AudioConversionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@RestController
@RequestMapping("/api/audio")
@CrossOrigin(origins = "*")
public class AudioController {

    @Autowired
    private AudioConversionService audioConversionService;

    /**
     * 上传并转换音频文件
     */
    @PostMapping("/convert")
    public ResponseEntity<Map<String, Object>> convertAudio(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "folderName", required = false) String folderName) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                response.put("success", false);
                response.put("message", "请选择要转换的文件");
                return ResponseEntity.badRequest().body(response);
            }

            // 检查文件格式
            if (!audioConversionService.isSupportedFormat(file.getOriginalFilename())) {
                response.put("success", false);
                response.put("message", "不支持的文件格式。支持的格式：m4a, wav, flac, aac, ogg, wma");
                return ResponseEntity.badRequest().body(response);
            }

            // 开始转换
            CompletableFuture<String> conversionFuture = audioConversionService.convertToMp3(file, folderName);
            
            // 尝试获取文件信息（如果失败不影响转换）
            AudioConversionService.AudioInfo audioInfo = null;
            try {
                audioInfo = audioConversionService.getAudioInfo(file);
            } catch (Exception e) {
                System.err.println("获取音频信息失败，但不影响转换: " + e.getMessage());
                // 创建默认的音频信息
                audioInfo = new AudioConversionService.AudioInfo();
                audioInfo.setDuration(0.0);
                audioInfo.setSize(file.getSize());
                audioInfo.setBitRate(0);
                audioInfo.setSampleRate(0);
                audioInfo.setChannels(0);
                audioInfo.setCodec("unknown");
            }
            
            response.put("success", true);
            response.put("message", "文件上传成功，正在转换...");
            response.put("originalFilename", file.getOriginalFilename());
            response.put("fileSize", file.getSize());
            response.put("audioInfo", audioInfo);
            response.put("conversionId", conversionFuture.hashCode());
            
            // 等待转换完成并返回结果
            String convertedFile = conversionFuture.get();
            response.put("convertedFile", convertedFile);
            
            // 添加文件名信息
            String originalFilename = file.getOriginalFilename();
            String convertedFilename = new java.io.File(convertedFile).getName();
            response.put("originalFilename", originalFilename);
            response.put("convertedFilename", convertedFilename);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            response.put("success", false);
            
            // 提供更具体的错误信息
            String errorMessage = e.getMessage();
            if (errorMessage.contains("Invalid data found when processing input")) {
                response.put("message", "文件可能已损坏或格式不支持。请检查文件完整性。");
            } else if (errorMessage.contains("No such file or directory")) {
                response.put("message", "文件路径错误，请重新上传文件。");
            } else if (errorMessage.contains("Permission denied")) {
                response.put("message", "文件访问权限不足，请检查文件权限。");
            } else if (errorMessage.contains("FLAC文件不包含有效的音频流")) {
                response.put("message", "FLAC文件已损坏或格式不正确，请使用有效的FLAC文件。");
            } else {
                response.put("message", "转换失败: " + errorMessage);
            }
            
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 批量下载转换后的文件
     */
    @PostMapping("/download-all")
    public ResponseEntity<Resource> downloadAllFiles(@RequestBody Map<String, Object> request) {
        try {
            // 这里应该实现ZIP文件创建逻辑
            // 暂时返回一个简单的响应
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "批量下载功能正在开发中");
            
            // 创建临时ZIP文件
            String zipPath = audioConversionService.createZipFile(request);
            Path filePath = Paths.get(zipPath);
            Resource resource = new FileSystemResource(filePath.toFile());
            
            if (resource.exists() && resource.isReadable()) {
                return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"converted_audio_files.zip\"")
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 下载转换后的文件
     */
    @GetMapping("/download/{filename}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String filename) {
        try {
            Path filePath = Paths.get("outputs", filename);
            Resource resource = new FileSystemResource(filePath.toFile());
            
            if (resource.exists() && resource.isReadable()) {
                return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 获取文件信息
     */
    @PostMapping("/info")
    public ResponseEntity<Map<String, Object>> getFileInfo(@RequestParam("file") MultipartFile file) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            if (file.isEmpty()) {
                response.put("success", false);
                response.put("message", "请选择文件");
                return ResponseEntity.badRequest().body(response);
            }

            AudioConversionService.AudioInfo audioInfo = audioConversionService.getAudioInfo(file);
            
            response.put("success", true);
            response.put("audioInfo", audioInfo);
            response.put("filename", file.getOriginalFilename());
            response.put("fileSize", file.getSize());
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            response.put("success", false);
            
            // 提供更具体的错误信息
            String errorMessage = e.getMessage();
            if (errorMessage.contains("Invalid data found when processing input")) {
                response.put("message", "文件可能已损坏或格式不支持。请检查文件完整性。");
            } else if (errorMessage.contains("No such file or directory")) {
                response.put("message", "文件路径错误，请重新上传文件。");
            } else if (errorMessage.contains("Permission denied")) {
                response.put("message", "文件访问权限不足，请检查文件权限。");
            } else if (errorMessage.contains("文件不包含有效的音频流")) {
                response.put("message", "文件不包含有效的音频数据，请检查文件格式。");
            } else {
                response.put("message", "获取文件信息失败: " + errorMessage);
            }
            
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 检查转换状态
     */
    @GetMapping("/status/{conversionId}")
    public ResponseEntity<Map<String, Object>> getConversionStatus(@PathVariable String conversionId) {
        Map<String, Object> response = new HashMap<>();
        
        // 这里可以实现更复杂的状态跟踪逻辑
        // 目前返回简单的状态信息
        response.put("success", true);
        response.put("status", "completed");
        response.put("message", "转换完成");
        
        return ResponseEntity.ok(response);
    }

    /**
     * 清理临时文件
     */
    @DeleteMapping("/cleanup")
    public ResponseEntity<Map<String, Object>> cleanupFiles() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 清理输出目录中的旧文件（超过1小时的文件）
            cleanupOldFiles("outputs");
            cleanupOldFiles("uploads");
            
            response.put("success", true);
            response.put("message", "清理完成");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "清理失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 清理旧文件
     */
    private void cleanupOldFiles(String directory) throws IOException {
        Path dirPath = Paths.get(directory);
        if (Files.exists(dirPath)) {
            Files.list(dirPath)
                .filter(path -> {
                    try {
                        long lastModified = Files.getLastModifiedTime(path).toMillis();
                        long currentTime = System.currentTimeMillis();
                        // 删除超过1小时的文件
                        return (currentTime - lastModified) > 3600000;
                    } catch (IOException e) {
                        return false;
                    }
                })
                .forEach(path -> {
                    try {
                        Files.delete(path);
                    } catch (IOException e) {
                        // 忽略删除失败的文件
                    }
                });
        }
    }

    /**
     * 检查系统状态
     */
    @GetMapping("/status")
    public ResponseEntity<Map<String, Object>> getSystemStatus() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            boolean ffmpegAvailable = audioConversionService.isFFmpegAvailable();
            String ffmpegVersion = audioConversionService.getFFmpegVersion();
            
            response.put("success", true);
            response.put("ffmpegAvailable", ffmpegAvailable);
            response.put("ffmpegVersion", ffmpegVersion);
            response.put("uploadDir", "uploads");
            response.put("outputDir", "outputs");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取系统状态失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
} 